
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/page/book_detail_page.dart';
import '../entity/book_entity.dart';
import '../hive/hive_helper.dart';
import '../main.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/device_name_widget.dart';
import 'help_page.dart';


class SearchBook extends StatefulWidget {
  const SearchBook({Key? key}) : super(key: key);

  @override
  State<SearchBook> createState() => _SearchBookState();
}

class _SearchBookState extends State<SearchBook> {

  late List<BookEntity> lists;
  final RxList<BookEntity> list = RxList();

  var pageIndex = 1.obs;
  var pageSize = 16;
  var totalPage = 1.obs;


  @override
  initState() {
    super.initState();
    lists = bookQueryAll().where((element) => element.statue == 0).toList();
    _subList();

    WidgetsBinding.instance.addPostFrameCallback((_){
      tts.speak("请选择想要借阅的图书");
      timer.startCountDown(CountDownMode.normal,(){
        Get.until((route) => route.isFirst);
      });
    });
  }

  _subList(){
    totalPage.value = lists.length~/pageSize;
    if(lists.length%pageSize != 0){
      totalPage.value++;
    }
    if(pageIndex.value<1){
      pageIndex.value = 1;
      toastWarn("已经是第一页");
    }
    if(lists.length > pageIndex.value*pageSize){
      list.clear();
      list.addAll(lists.sublist((pageIndex.value-1)*pageSize,pageIndex.value*pageSize));
    }else if(lists.length <= pageIndex.value*pageSize && lists.length > (pageIndex.value-1)*pageSize){
      list.clear();
      list.addAll(lists.sublist((pageIndex.value-1)*pageSize,lists.length));
    }else{
      pageIndex.value--;
      // toastWarn("已经是最后一页");
    }

  }


  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          InkWell(
            onTap: (){
              Get.to(()=> const Help());
            },
            child:  Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [

                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              timer.cancel();
              Get.back();
            },
            child: _image("assets/images/back.png",60.w,23.h),
          ),
          _image("assets/images/type_book_title.png",90.w,21.h),
          Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
        ],
      )
    );
  }

  _searchBarWidget(){
    return Container(
      decoration:BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(16.r)),
      ),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
      margin:  EdgeInsets.only(left: 20.w, right: 20.w, bottom: 15.h,top: 15.h),
      child: Row(
        children: [
          _image("assets/images/search_icon.png",18.w,18.h),
          SizedBox(width: 4.w,),
          Container(
            width: 240.w,
            child: TextField(
                minLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (input){
                  // _keyWord = input;
                  if(input.isNotEmpty){
                    lists = bookQueryByKey(input).where((element) => element.statue == 0).toList();
                  }else{
                    lists = bookQueryAll().where((element) => element.statue == 0).toList();
                  }
                  pageIndex.value =1;
                  _subList();
                },
                decoration: const InputDecoration(
                  isCollapsed: true,
                  border: InputBorder.none,
                  hintText: "按 书名 作者 索书号等关键字 检索",
                ),

                style: TextStyle(color: Colors.black,fontSize: 12.sp)
            ),

          ),
        ],
      )
    );
  }

  _subTitle(String? title){
    if(title != null && title.length >8){
      return title.substring(0,8);
    }
    return title;
  }

  _itemBuilder(index){
    var item = list[index];
    return InkWell(
      onTap: (){
        Get.to(() => const BookDetail(),arguments: item);
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          item.cover!= null?Image.memory(base64Decode(item.cover??''),
              gaplessPlayback: true,//防止重绘
              width: 70.w,
              height: 89.h,
              fit: BoxFit.cover,
            ):Image.asset("assets/images/default.jpg",height: 89.h, width: 70.w, fit: BoxFit.fill,),
          SizedBox(height: 2.h,),
          Expanded(child: Text('《${_subTitle(item.mainTitle)}》',overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 7.sp),),)
        ],
      ),
    );
  }

  _booksContainer(){
    return Container(
      decoration:BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      margin: EdgeInsets.only(left: 20.w,right: 20.w),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.h,bottom: 6.h),
      width: double.infinity,
      height: 442.h,

      child: Obx(() => GridView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: list.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:0.67,  crossAxisSpacing: 8.w, mainAxisSpacing: 5.h),
      ),)
    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: (){
            pageIndex.value--;
            _subList();
          },
          child:  _image("assets/images/previous.png", 80.w, 36.h),
        ),
        SizedBox(width: 20.w,),
        Obx(() => Text("${pageIndex.value}/${totalPage.value}",style: TextStyle(fontSize: 10.sp),),),
        SizedBox(width: 20.w,),
        InkWell(
          onTap: (){
            pageIndex.value++;
            _subList();
          },
          child:   _image("assets/images/next.png", 80.w, 36.h),
        )
      ],
    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _searchBarWidget(),
            _booksContainer(),
            SizedBox(height: 10.h,),
            _action(),
          ],
        ),
      ),
    );
  }
}

